<template>
  <div class="preview">
    <br><br>
    <div class="p-main">
        <div class="p-title" style="font-size:30px;font-weight:bold;color:#0095ff;padding-top:20px;">{{title}}</div>
      <br><br>

      <div style="height:50px;margin-left:650px;" v-show="this.ntype=='E'">
          <div style="font-size: 16px;color: #666;">剩余时间</div>
          
           <div class="time" style="color:red;margin-left:-20px;font-size: 18px;margin-top:10px;">&nbsp;&nbsp;<i class="el-icon-time"></i>{{hr}}小时 {{min}}分钟 {{sec}}秒 </div>

      </div>
      
      <el-card
        v-for="(item,index) in arr"
        shadow="never"
        :key="index"
        style="margin: 0;border:none;padding-left:50px;"
      >

        <template v-if="ntype=='A' &&item.type == 'S'">
          <norm-single
            :item="item"
            :auto-id="showId"
            :num="index"
          ></norm-single>
        </template>

        <!--        单选-->
        <template v-else-if="item.type == 'S'">
          <p-single-choice
            :item="item"
            :auto-id="showId"
            :num="index"
            @sendanswer="saveanswer"
          ></p-single-choice>
        </template>

         <template v-else-if="ntype=='A'&&item.type == 'M'">
          <norm-mul :item="item" 
          :num="index" 
          :auto-id="showId"></norm-mul> 
        </template>

        <!--        多选-->
        <template v-else-if="item.type == 'M'">
          <p-mul-choice :item="item" 
          :num="index" 
          :auto-id="showId"
          @sendanswer="saveanswer"
          ></p-mul-choice>
        </template>

       <template v-else-if="( item.type == 'F' && item.is_location == true)">
          <position-b-m
            :item="item"
            :num="index"
            :showId="showId"
            :auto-id="showId"
          ></position-b-m>
        </template>  

        <!--        填空-->
        <template v-else-if="item.type == 'F'">
          <p-single-tiankong
            :item="item"
            :num="index"
            :auto-id="showId"
            @sendanswer="saveanswer"
          ></p-single-tiankong>
        </template>

        <!--        评分-->
        <template v-else-if="item.type == 'R'">
          <p-rate-slider
            :item="item"
            :num="index"
    
            :auto-id="showId"
            @sendanswer="saveanswer"
          ></p-rate-slider>
        </template>
      </el-card>
      <div class="submit" style="margin-top:30px;padding-bottom:20px;">
        <el-button type="primary" @click="submit">提交</el-button>
    </div>
    </div>

    
  </div>
</template>


<script>
import PSingleChoice from '@/components/PreviewFinal/PSingleChoice'

import PMulChoice from '@/components/PreviewFinal/PMulChoice'
import PSingleTiankong from '@/components/PreviewFinal/PSingleTiankong'
import PRateSlider from '@/components/PreviewFinal/PRateSlider'
import PositionBM from '@/components/Clock/PositionBM'
import NormMul from '@/components/Enroll/NormMul'
import NormSingle from '@/components/Enroll/NormSingle'
import {GetAllQuestionInfoWithoutUid,SubmitAllAnswer,SubmitExamAnswer} from "../../api";
export default {
    name: "editbody",
    components: {
    PSingleChoice,
    PMulChoice,
    PSingleTiankong,
    PRateSlider,
    PositionBM,
    NormMul,
    NormSingle

    },
    data() {
    return {
        arr:[],
        questionnaire_id:0,
        title:'',
        showId: true,
        qid:'',
        AllAnwser:[],
        day:0,
        hr:0,
        min:0,
        sec:0,
        isexam:true,

        ntype:"",
        deadtime:"",
        isApply:""
    }
},
    async mounted() {
        let id = JSON.parse(this.$UrlEncode.decode(this.$route.query.qid))
        this.questionnaire_id=id/1234;
        const result=await GetAllQuestionInfoWithoutUid(this.questionnaire_id)
        console.log(result)
        this.arr=result.question_list
        console.log(this.arr)
        this.title=result.questionnaire_title
        this.showId=result.is_order
        this.ntype=result.type
        this.deadtime=result.deadline
        //判断是否是考试


        if(result.ntyoe=='E'){
          this.countdown();
        }

    },
    methods: {
        close(){
            this.$router.back(-1)
        },
        async submit(){
            
            const ip=localStorage.getItem('Ip')
          //  console.log(returnCitySN["cip"])
            console.log(ip)

            if(this.ntype=="E"){
                const result=await SubmitExamAnswer(this.questionnaire_id, this.AllAnwser, ip, -1)
                console.log(result)
                if(result.error_code==0){
                  this.$message({
                  message: '交卷成功',
                  type: 'success'
                })
                else if(result.error_code==0){
                  
                }
                let qid = result.answersheet_id*1234;
                var encode_str=this.$UrlEncode.encode(JSON.stringify(qid));

                this.$router.push({
                    path: "/examfinish",
                    query:{
                        questionnaireId: encode_str
                    }
                  });
                }
                else{
                  alert("failed")
                }
              
            }
            else if(this.ntype=="N"){
              const result=await SubmitAllAnswer(this.questionnaire_id,this.AllAnwser,ip,-1)
              console.log(result)
              if(result.error_code==0){
                this.$message({
                message: '交卷成功',
                type: 'success'
              });
                this.$router.replace('/normalfinish');
              }
              else{
                alert("failed")
              }
            }
            else if(this.ntype=="V"){
              const result=await SubmitAllAnswer(this.questionnaire_id,this.AllAnwser,ip,-1)
              console.log(result)
              if(result.error_code==0){
                this.$message({
                message: '交卷成功',
                type: 'success'
              });
                const vid= result.answersheet_id*1234;
                var vencode_str=this.$UrlEncode.encode(JSON.stringify(vid));

                this.$router.push({
                    path: "/votefinish",
                    query:{
                        questionnaireId: vencode_str
                    }
                  });
              }
              else{
                alert("failed")
              }
            }
            

        },
        saveanswer(data){
          console.log('aaa')
          console.log(data)
          var i;
          for(i=0;i<this.AllAnwser.length;i++)
          {
            if(this.AllAnwser[i].id === data.id){
              this.AllAnwser[i].answer=data.answer;
              break;
            }
          }
          if(i==this.AllAnwser.length){
            this.AllAnwser.push(data)
          }
          console.log(this.AllAnwser)
        },
        countdown () {
          const end = Date.parse(new Date(this.deadtime))
          const now = Date.parse(new Date())
          const msec = end - now

          //console.log(msec)
          if(msec<0) return;

          let day = parseInt(msec / 1000 / 60 / 60 / 24)
          let hr = parseInt(msec / 1000 / 60 / 60 % 24)
          let min = parseInt(msec / 1000 / 60 % 60)
          let sec = parseInt(msec / 1000 % 60)
          this.day = day
          this.hr = hr > 9 ? hr : '0' + hr
          this.min = min > 9 ? min : '0' + min
          this.sec = sec > 9 ? sec : '0' + sec
          const that = this
          if(min>=0 && sec>=0){
            //倒计时结束关闭订单
            if(min==0 && sec==0){

              return
            }
            setTimeout(function () {
              that.countdown()
            }, 1000)
          }
        },
        datarefresh(){
          if (this.intervalId != null) {
            return;
          }
          // 计时器为空，操作
          this.intervalId = setInterval(() => {
            console.log("刷新" + new Date());
            this.initData(); //加载数据函数
          }, 2000)
        },
        clear(){
          clearInterval(this.intervalId); //清除计时器
          this.intervalId = null; 
        },
        async initData(){
          const result=await GetAllQuestionInfoWithoutUid(this.questionnaire_id)
          
          console.log(result)
          this.arr=result.question_list
          this.$forceUpdate()
        }

    },
    created(){
      if(this.ntype=='A'){
          this.datarefresh();
        }
      
    },
    destroyed(){
      if(this.ntype=='A')
      {
          this.clear();
      }
      
    }
};
</script>

<style scoped>
.preview {
  height: 100%;
  width: 100%;
  background-color: #d1e9fa;
  overflow: auto;
}
.p-head {
  width: 100%;
  height: 7%;
  background-color: #fff;
  
}
.p-main {
  min-height: 700px;
  width: 60%;
  background-color: #fff;
  margin: 0 auto;
  
}
</style>